<template>
  <div class="condition-set-container">
    <ul class="condition-set-top scroll-box">
      <li>
        <p class="tag-name">设备类型</p>
        <div
          class="tag-content"
          @click="chooseCondition(1)"
        >
          <span
            class="color-black"
            v-if="typeName"
          >{{ typeName }}</span>
          <span
            class="color-gray"
            v-else
          >请选择</span>
          <van-icon name="arrow" />
        </div>
      </li>
      <li>
        <p class="tag-name">物模型</p>
        <div
          class="tag-content"
          @click="chooseCondition(2)"
        >
          <span
            class="color-black"
            v-if="modelName"
          >{{ modelName }}</span>
          <span
            class="color-gray"
            v-else
          >请选择</span>
          <van-icon name="arrow" />
        </div>
      </li>
      <li>
        <p class="tag-name required">选择设备</p>
        <div
          class="tag-content"
          @click="chooseCondition(3)"
        >
          <span
            class="color-black"
            v-if="deviceName"
          >{{ deviceName }}</span>
          <span
            class="color-gray"
            v-else
          >请选择</span>
          <van-icon name="arrow" />
        </div>
      </li>
      <li>
        <p class="tag-name required">开始时间</p>
        <div
          class="tag-content"
          @click="chooseDatetime(1)"
        >
          <span v-if="startTime">{{ startTime }}</span>
          <span
            class="color-gray"
            v-else
          >请选择</span>
          <van-icon name="arrow" />
        </div>
      </li>
      <li>
        <p class="tag-name required">结束时间</p>
        <div
          class="tag-content"
          @click="chooseDatetime(2)"
        >
          <span v-if="endTime">{{ endTime }}</span>
          <span
            class="color-gray"
            v-else
          >请选择</span>
          <van-icon name="arrow" />
        </div>
      </li>
      <li>
        <p class="tag-name required">时间间隔</p>
        <div
          class="tag-content"
          @click="chooseCondition(4)"
        >
          <span
            class="color-black"
            v-if="gapName"
          >{{ gapName }}</span>
          <span
            class="color-gray"
            v-else
          >请选择</span>
          <van-icon name="arrow" />
        </div>
      </li>
      <li>
        <p class="tag-name required">
          <span>选择变量</span>
          <span class="color-gray">已选择：<i class="color-primary">{{ chooseVarData.length }}</i>/5</span>
        </p>
        <div class="tag-content choose-var">
          <div
            class="var-item"
            v-for="(item, index) in chooseVarData"
            :key="index"
          >
            <span>{{ item.vname }}</span>
            <van-icon
              name="cross"
              @click="deleteVarData(item)"
            />
          </div>
          <van-button
            plain
            @click="openChooseVar"
            v-if="chooseVarData.length < 5"
          >选择变量</van-button>
        </div>
      </li>
    </ul>

    <div class="submit-box border-top">
      <van-button
        type="primary"
        block
        @click="cancelCondition"
        class="cancel-btn"
      >取 消</van-button>
      <van-button
        type="primary"
        block
        @click="submitFn"
      >确 定</van-button>
    </div>

    <!-- 各选项列表弹窗 -->
    <van-action-sheet
      v-model="showActionSheet"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      :description="description"
      @select="selectSheet"
      @cancel="onCancel"
    />

    <!-- 日期弹窗 -->
    <van-popup
      v-model="showDateTimePicker"
      position="bottom"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        :title="datetimePickerTitle"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmFn"
        @cancel="cancelFn"
      />
    </van-popup>

    <!-- 变量弹窗 -->
    <van-popup
      v-model="showVarPopup"
      position="bottom"
      :close-on-click-overlay="false"
      :style="{ height: '64%' }"
    >
      <div class="var-box">
        <div class="var-box-header">
          <span class="model-name">{{ deviceModelName || '' }}</span>
          <p class="model-choose">已选择（<span class="color-primary">{{ chooseVarData.length }}</span>/5）</p>
        </div>
        <div class="var-search-box">
          <form action="/">
            <van-search
              v-model="searchKey"
              shape="round"
              placeholder="输入变量名称查找"
              clearable
              @search="handleSearch"
              @clear="handleClear"
            />
          </form>
        </div>
        <ul class="var-list scroll-box">
          <li
            v-for="(item, index) in filterVarList"
            :key="item.vname"
            :class="{'color-primary': item.checked}"
            @click="selectVar(item, index)"
          >
            <span>{{ item.vname}}</span>
            <van-icon
              name="success"
              v-if="item.checked"
            />
          </li>
        </ul>
        <ul class="operate-box">
          <li @click="cancelSelect">取消</li>
          <li
            class="color-primary"
            @click="confirmSelect"
          >确定</li>
        </ul>
      </div>
    </van-popup>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { Button, Icon, ActionSheet, Popup, DatetimePicker, Search } from 'vant';
import { getModelGroupList, getModelList, getDeviceList, getModelVariable } from '@/api/historyData.js';

export default {
  name: 'ConditionSet',
  components: {
    [Button.name]: Button,
    [Icon.name]: Icon,
    [ActionSheet.name]: ActionSheet,
    [Popup.name]: Popup,
    [DatetimePicker.name]: DatetimePicker,
    [Search.name]: Search
  },
  data() {
    return {
      showActionSheet: false,
      type: '',
      description: '',
      actions: [],
      typeName: '',
      typeValue: '',
      typeActions: [],
      modelName: '',
      modelValue: '',
      modelActions: [],
      deviceName: '',
      deviceValue: '',
      deviceNumber: '',
      deviceActions: [],
      gapName: '',
      gapValue: '',
      gapActions: [],
      showDateTimePicker: false,
      datetimePickerTitle: '',
      datetimeType: '',
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      startTime: '',
      endTime: '',
      showVarPopup: false,
      searchKey: '',
      varTotal: 0,
      varList: [],
      filterVarList: [],
      deviceModelId: '',
      deviceModelName: '',
      chooseVarData: [],
      oldChooseVarData: []
    };
  },
  created() {
    this.getModelGroupList();
    this.getModelList();
    this.getDeviceList();
    this.createGapActions();
  },
  methods: {
    // 获取物模型分类列表
    getModelGroupList() {
      getModelGroupList().then(res => {
        if (res.data && res.data.length) {
          res.data.map(item => {
            this.typeActions.push({
              name: item.name,
              value: item.id
            });
          });
        }
      });
    },
    // 获取物模型列表
    getModelList() {
      getModelList({
        id: this.typeValue || 0
      }).then(res => {
        if (res.data && res.data.length) {
          res.data.map(item => {
            this.modelActions.push({
              name: item.name,
              value: item.id
            });
          });
        }
      });
    },
    // 获取设备列表
    getDeviceList() {
      getDeviceList({
        typeId: this.typeValue,
        modelId: this.modelValue
      }).then(res => {
        if (res.data.list && res.data.list.length) {
          res.data.list.map(item => {
            this.deviceActions.push({
              name: item.name,
              value: item.id,
              number: item.number,
              deviceModelId: item.modelId,
              deviceModelName: item.modelName
            });
          });
        }
      });
    },
    // 创建时间间隔选项
    createGapActions() {
      this.gapActions = [
        {
          name: '时',
          value: 'hours'
        },
        {
          name: '分',
          value: 'minutes'
        },
        {
          name: '秒',
          value: 'seconds'
        }
      ];
    },
    // 获取物模型变量
    getModelVariable() {
      getModelVariable({
        id: this.deviceModelId
      }).then(res => {
        if (res.data && res.data.length) {
          this.varList = res.data;
          this.varList.map(item => {
            item.checked = false;
          });
          this.filterVarList = JSON.parse(JSON.stringify(this.varList));
          if (this.chooseVarData.length) {
            this.chooseVarData.map(item => {
              this.filterVarList.map(ii => {
                if (ii.vname === item.vname) {
                  ii.checked = item.checked;
                }
              });
            });
          }
        }
      });
    },
    // 选择条件
    chooseCondition(type) {
      // type 1设备类型 2物模型 3选择设备 4时间间隔
      let descriptionArr = ['设备类型', '物模型', '选择设备', '时间间隔'];
      this.description = descriptionArr[type - 1];
      switch (type) {
        case 1:
          this.actions = this.typeActions;
          break;
        case 2:
          this.actions = this.modelActions;
          break;
        case 3:
          this.actions = this.deviceActions;
          break;
        case 4:
          this.actions = this.gapActions;
          break;
      }

      this.showActionSheet = true;
      this.type = type;
    },
    // 选择选项
    selectSheet(action, index) {
      // type 1设备类型 2物模型 3选择设备 4时间间隔
      switch (this.type) {
        case 1:
          this.typeName = action.name;
          this.typeValue = action.value;
          break;
        case 2:
          this.modelName = action.name;
          this.modelValue = action.value;
          break;
        case 3:
          this.deviceName = action.name;
          this.deviceValue = action.value;
          this.deviceNumber = action.number;
          this.deviceModelId = action.deviceModelId;
          this.deviceModelName = action.deviceModelName;
          break;
        case 4:
          this.gapName = action.name;
          this.gapValue = action.value;
          break;
      }
    },
    // 取消选项选择
    onCancel() {
      this.showActionSheet = false;
    },
    // 选择起止时间
    chooseDatetime(type) {
      this.datetimePickerTitle = type === 1 ? '选择开始时间' : '选择结束时间';
      this.datetimeType = type;
      this.showDateTimePicker = true;
    },
    // 确认时间选择
    confirmFn(value) {
      let dateTime = dayjs(value).format('YYYY/MM/DD HH:mm');
      if (this.datetimeType === 1) {
        this.startTime = dateTime + ':00';
      } else {
        this.endTime = dateTime + ':59';
      }
      this.showDateTimePicker = false;
    },
    // 取消时间选择
    cancelFn() {
      this.showDateTimePicker = false;
    },
    // 删除所选变量
    deleteVarData(item) {
      this.chooseVarData.map((ii, idx) => {
        if (ii.vname === item.vname) {
          this.chooseVarData.splice(idx, 1);
        }
      });
    },
    // 打开选择变量
    openChooseVar() {
      if (this.deviceName) {
        this.showVarPopup = true;
        this.getModelVariable();
        this.oldChooseVarData = JSON.parse(JSON.stringify(this.chooseVarData));
      } else {
        this.$toast('请先选择设备');
      }
    },
    // 搜索变量
    handleSearch() {
      let filterArr = this.varList.filter(item => {
        return item.vname.indexOf(this.searchKey) !== -1;
      });
      this.filterVarList = filterArr;
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.filterVarList.map(ii => {
            if (ii.vname === item.vname) {
              ii.checked = item.checked;
            }
          });
        });
      }
    },
    // 清空搜索
    handleClear() {
      this.filterVarList = this.varList;
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.filterVarList.map(ii => {
            if (ii.vname === item.vname) {
              ii.checked = item.checked;
            }
          });
        });
      }
    },
    // 选择变量
    selectVar(item, index) {
      if (!item.checked) {
        if (this.chooseVarData.length === 5) {
          this.$toast('最多选择5个变量');
          return;
        }
      }

      item.checked = !item.checked;
      this.$forceUpdate();
      if (item.checked) {
        this.chooseVarData.push(item);
      } else {
        this.chooseVarData.map((ii, idx) => {
          if (ii.vname === item.vname) {
            this.chooseVarData.splice(idx, 1);
          }
        });
      }
    },
    // 取消变量选择
    cancelSelect() {
      if (this.oldChooseVarData.length === 0) {
        this.chooseVarData = [];
      }
      this.showVarPopup = false;
    },
    // 确定变量选择
    confirmSelect() {
      this.showVarPopup = false;
    },
    // 取消条件设置
    cancelCondition() {
      this.$emit('cancel');
    },
    // 提交所选条件
    submitFn() {
      if (!this.deviceName) {
        this.$toast('请选择设备');
        return;
      }
      if (!this.startTime) {
        this.$toast('请选择开始时间');
        return;
      }
      if (!this.endTime) {
        this.$toast('请选择结束时间');
        return;
      }
      if (!this.gapValue) {
        this.$toast('请选择时间间隔');
        return;
      }
      if (!this.chooseVarData.length) {
        this.$toast('请选择变量');
        return;
      }

      let params = [];
      this.chooseVarData.map(item => {
        let obj = {
          product_id: this.deviceModelId + '',
          device_id: this.deviceValue + '',
          point: item.vk,
          type: item.vtype
        };
        params.push(obj);
      });

      let conditionData = {
        deviceName: this.deviceName,
        deviceValue: this.deviceValue,
        deviceNumber: this.deviceNumber,
        deviceModelId: this.deviceModelId,
        deviceModelName: this.deviceModelName,
        startTime: this.startTime,
        endTime: this.endTime,
        dimension: this.gapValue,
        chooseVarData: this.chooseVarData,
        params
      };
      localStorage.setItem('conditionData', JSON.stringify(conditionData));
      this.$emit('submit', conditionData);
    }
  }
};
</script>

<style lang="scss" scoped>
.condition-set-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-color: #fff;

  .condition-set-top {
    flex: 1;
    padding: 0 0.426667rem;

    li {
      padding: 0.32rem 0;
      border-bottom: 1px solid var(--border-color);

      .tag-name {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.426667rem;
        color: var(--color-deep-gray);
        font-size: 0.346667rem;

        &.required {
          position: relative;
          padding-left: 0.16rem;

          &::before {
            content: '*';
            position: absolute;
            left: 0;
            color: #f56c6c;
          }
        }

        span {
          &:last-of-type {
            i {
              font-size: 0.373333rem;
              font-style: normal;
            }
          }
        }
      }
      .tag-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 0.373333rem;

        &.choose-var {
          display: flex;
          flex-direction: column;
          align-items: flex-start;

          .var-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            height: 0.96rem;

            .van-icon {
              color: #85aeff;
            }
          }

          .van-button {
            width: 2.293333rem;
            height: 0.853333rem;
            margin: 0.32rem 0;
            padding: 0;
            border-radius: 0.08rem;
            border: 1px solid var(--color-primary);
            color: var(--color-primary);

            &::before {
              background-color: var(--color-primary);
            }
          }
        }

        .van-icon {
          color: #ccc;
        }
      }
    }
  }

  .van-popup--bottom {
    border-top-left-radius: 0.426667rem;
    border-top-right-radius: 0.426667rem;

    .var-box {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;

      .var-box-header {
        flex-shrink: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.213333rem;
        padding: 0 0.426667rem;
        padding-top: 0.426667rem;

        .model-name {
          margin-right: 0.266667rem;
          font-size: 0.426667rem;
          line-height: 0.533333rem;
        }

        .model-choose {
          flex-shrink: 0;
          color: var(--color-gray);
          font-size: 0.32rem;

          span {
            font-size: 0.373333rem;
          }
        }
      }

      .var-search-box {
        flex-shrink: 0;
        margin-bottom: 0.213333rem;
        border-bottom: 1px solid var(--border-color);
      }

      .var-list {
        flex: 1;
        width: 100%;
        padding: 0 0.426667rem;

        li {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0.32rem 0;
          font-size: 0.373333rem;
          border-bottom: 1px solid var(--border-color);

          &:last-of-type {
            border-bottom: 0;
          }
        }
      }

      .operate-box {
        flex-shrink: 0;
        display: flex;
        width: 100%;
        height: 1.28rem;
        border-top: 1px solid var(--border-color);

        li {
          position: relative;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 50%;
          font-size: 0.426667rem;

          &:first-of-type {
            &::after {
              content: '';
              position: absolute;
              top: 0;
              right: 0;
              width: 1px;
              height: 100%;
              background-color: var(--border-color);
            }
          }
        }
      }
    }
  }

  .submit-box {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 1.493333rem;
    padding: 0.213333rem 0.426667rem;
    background-color: #fff;

    .van-button {
      width: 4.32rem;
      padding: 0;
      color: #fff;
      border-radius: 0.08rem;
      border-color: var(--color-primary);
      background-color: var(--color-primary);

      &.cancel-btn {
        color: var(--color-deep-gray);
        background-color: #fff;
        border: 1px solid var(--border-color);
      }
    }
  }
}
</style>